import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;


@SuppressWarnings("serial")
public class Cantor extends JPanel implements ActionListener {
	JLabel kortees, vastus;
	JButton vasta;
	JTextField k, v;
	boolean tsykkel;
	String sisu;

	public Cantor() {
		setLayout(new GridLayout(2,2));
        JPanel p6hipaneel = new JPanel();
        p6hipaneel.setLayout(new FlowLayout(FlowLayout.LEADING));
		// LAHTRID
		JPanel korteesid = new JPanel(new FlowLayout(FlowLayout.LEADING));
		kortees = new JLabel("Korteež: ");
		k = new JTextField(10);
		
		korteesid.add(kortees);
		korteesid.add(k);
		
		vastus = new JLabel("Vastus: ");
		v = new JTextField(10);
		v.setEditable(false);
		
		JPanel vastused = new JPanel(new FlowLayout());
	    vastused.add(vastus);
		vastused.add(v);
		// END OF: LAHTRID
        
		

		// VASTA NUPP
		vasta = new JButton("Arvuta");
		vasta.addActionListener(this);
		//lahtripaneel.add(vasta);
		p6hipaneel.add(korteesid);
		p6hipaneel.add(vasta);
		p6hipaneel.add(vastused);
		JLabel manual = new JLabel("Sisesta korteež kujul näiteks <<5,1>,2>");
		p6hipaneel.add(manual);
		add(p6hipaneel);
		JPanel tyh1 = new JPanel();
		add(tyh1);
		JPanel tyh2 = new JPanel(new FlowLayout());
		
		
		add(tyh2);
		JPanel tyh3 = new JPanel();
		add(tyh3); 
		
		
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand() == "Arvuta") {
			tsykkel = true;
			sisu = k.getText();
			while(tsykkel){
				Pattern pattern = Pattern.compile("<[\\d]{1,},[\\d]{1,}>");
				Matcher matcher = pattern.matcher(sisu);
				if (matcher.find()) {
					String numbrid = matcher.group(0);
					String numbridt = matcher.group(0);
					numbridt = numbridt.replace("<", "");
					numbridt = numbridt.replace(">", "");
					String[] number = numbridt.split(",");
					int esimene = Integer.parseInt(number[0]);
					int teine = Integer.parseInt(number[1]);
					int a = esimene+teine;
					int b = a+1;
					int c = a*b;
					int d = c/2;
					int vastust = d+esimene;
					sisu = sisu.replace(numbrid, vastust+"");
				}else{
					tsykkel = false;
				}
			}
			v.setText(sisu);
		}
	}
}